package com.dhcc.core.framework.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {

	public static String encryptByAES(String input, String key)
		    throws Exception
		  {
		    String algorithm = "AES";
		    String transformation = "AES";

		    Cipher cipher = Cipher.getInstance(transformation);

		    SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);

		    cipher.init(1, sks);

		    byte[] bytes = cipher.doFinal(input.getBytes());
		    return bytesToHexString(bytes);
		  }

		  public static String decryptByAES(String input, String key)
		    throws Exception
		  {
		    String algorithm = "AES";
		    String transformation = "AES";

		    Cipher cipher = Cipher.getInstance(transformation);

		    SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);

		    cipher.init(2, sks);

		    byte[] inputBytes = hexStringToBytes(input);
		    byte[] bytes = cipher.doFinal(inputBytes);
		    return new String(bytes);
		  }

		  private static byte[] hexStringToBytes(String hexString) {
		    if (hexString.length() % 2 != 0) throw new IllegalArgumentException("hexString length not valid");
		    int length = hexString.length() / 2;
		    byte[] resultBytes = new byte[length];
		    for (int index = 0; index < length; index++) {
		      String result = hexString.substring(index * 2, index * 2 + 2);
		      resultBytes[index] = Integer.valueOf(Integer.parseInt(result, 16)).byteValue();
		    }
		    return resultBytes;
		  }

		  private static String bytesToHexString(byte[] sources) {
		    if (sources == null) return null;
		    StringBuilder stringBuffer = new StringBuilder();
		    for (byte source : sources) {
		      String result = Integer.toHexString(source & 0xFF);
		      if (result.length() < 2) {
		        result = new StringBuilder().append("0").append(result).toString();
		      }
		      stringBuffer.append(result);
		    }
		    return stringBuffer.toString();
		  }
}
